#include "minicon.h"
#include "miniopt.h"

extern int err_ret(int errcode, const char *msg, const WCHAR *name);

//=============================================================================

static int create_dir( const WCHAR * dir, bool verbose )
{
   if ( verbose )
   {
      Con::o("create directory: \""); Con::o(dir); Con::o("\" -- ");
   }
   
   BOOL res = ::CreateDirectoryW(dir, NULL);

   if ( verbose )
   {
      Con::o(res ? "ok" : "failed"); Con::n();
   }

   if ( res )
      return 0;
   else
      return err_ret(-21, "Can't create", dir);
}

//=============================================================================

int mkdir( WCHAR **args, int na, bool parents, bool verbose )
{
   int i, rc;
   if ( na <= 0 )
      return Opt::opt_err(Opt::Err_Missed_Param);

   for ( rc = i = 0; i < na && rc == 0; ++i )
   {
      WCHAR wc, *pw, *dir = args[i];
      pw = dir + ::lstrlenW(dir) - 1;
      if ( pw >= dir && (L'\\' == *pw || L'/' == *pw) ) *pw = L'\0';

      if ( parents )
      {
         for ( pw = dir; *pw; )
         {
            while ( L'\\' == *pw || L'/' == *pw ) ++pw;
            while ( *pw && L'\\' != *pw && L'/' != *pw ) ++pw;
            wc = *pw;
            *pw = L'\0';
            if ( !Win::exists(dir, FILE_ATTRIBUTE_DIRECTORY) )
            {
               rc = create_dir( dir, verbose );
            }
            *pw = wc;
            if ( rc < 0 )
               break;
         }
      }

      else
      {
         rc = create_dir( dir, verbose );
      }
   }

   return rc;
}

//=============================================================================
